#!/bin/sh
# mounts and returns mount point
# return mount point if partition already mounted
# any error: return -ne 0

mntfunc() {
 MNT_T="$1"    #ex: vfat
 MNT_DEV="$2"  #ex: /dev/sda1
 MNT_DIR="$3"  #ex: /mnt/sda1
 case $MNT_T in
  ntfs)
   ntfs-3g $MNT_DEV $MNT_DIR -o umask=0,no_def_opts,noatime,rw,silent 2>/dev/null
   ntfsRETVAL=$?
   [ $ntfsRETVAL -eq 0 ] && return 0
   if [ $ntfsRETVAL -eq 14 ];then
    echo "ERROR: Windows NTFS hibernated partition, cannot mount" >&2
    return 14
   else
    ntfs-3g $MNT_DEV $MNT_DIR -o umask=0,no_def_opts,noatime,rw,force,silent 2>/dev/null
   fi
  ;;
  exfat) mount.exfat-fuse "$MNT_DEV" "$MNT_DIR" ;;
  *) mount -t $MNT_T $MNT_DEV $MNT_DIR ;;
 esac
 return $?
}

#-----------------------------------------------------

[ "$1" = "" ] && exit 1

xpart=$(echo "$1" | sed 's|/dev/||')

if [ ! -b /dev/$xpart ] ; then
  echo "$xpart: not a valid partition" &>2
  exit 1
fi

MP=$(mount | grep "^/dev/$xpart " | cut -f 3 -d ' ')

if [ "$MP" = "" ] ; then
  MP=/mnt/$xpart
  echo "* Mounting $xpart" >&2
  mkdir -p ${MP}
  fs=$(blkid /dev/$xpart 2>/dev/null | grep -o ' TYPE=".*"' | cut -f 2 -d '"')
  echo "fs=${fs}" >&2
  mntfunc $fs /dev/$xpart ${MP}
  if [ $? -ne 0 ] ; then
    echo "Coult not mount $xpart... sorry" >&2
    exit 1
  fi
fi

[ "$MP" = "" ] && exit 1

echo $MP

### END ###